import {
  adList
} from "../../utils/adConfig.js";
import {
  requst_post_addPoint,
  requst_post_likePic,
} from '../../utils/api.js'


var app = getApp();
// 在页面中定义激励视频广告
// 在页面中定义插屏广告
let interstitialAd = null;
let videoAd = null;
Page({
  data: {
    appTips: !0,
    src: "",
    item: "",
    adUnitId: "",
    is_credit: false,
    count: "0",
    user: "",
    bannerVideo: adList().bannerVideo,
    bannerAd: adList().bannerAd
  },
  onLoad: function (t) {
    console.log("详情",t)
    this.createAdView();
    var path = t.src;
    var picId = t.picId;

    if (null != path && this.setData({
        src: path,
        picId: picId,
      }), null != t.item) {
      var c = JSON.parse(t.item);
      this.setData({
        item: c,
        picId: c.sid,
      });
    }
    this.setData({
      userInfo: app.globalData.userInfo,
    })

  },
  createAdView: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    var that = this;
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: adList().tanchuangAd
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {
        console.log('err',err)
      })
      interstitialAd.onClose(() => {})
    }
    //创建广告
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: adList().videoAd
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {
        wx.showToast({
          title: '广告加载失败，稍后来试哦~',
          icon: 'none'
        })
      })
      videoAd.onClose((res) => {
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励

          that.addUserPoint(app.globalData.plusPoint, app.globalData.adAddPoint, "视频广告激励积分")
        } else {
          // 播放中途退出，不下发游戏奖励
          wx.showToast({
            title: '看完才能获得奖励哦~',
            icon: 'error'
          })
        }
      })
    }
  },

  onReady: function () {},
  onShow: function () {
    setTimeout(()=>
    {
     // 在适合的场景显示插屏广告
    var a = Math.ceil(Math.random() * 10);
    console.log(a)
    if (a <= 8) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })}
    }, 2000)
  },
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  showmode() {
    var that = this;
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        is_credit: !0,
      })
    } else {
      app.loginWx();
    }

    if (that.data.item) {
      var secondPicPath = that.data.item.avatar
      var mainPicPath = that.data.item.card
      that.setData({
        secondPicPath: secondPicPath,
        mainPicPath: mainPicPath
      })
    }
  },
  addUserPoint: function (type, point, pointDesc) {
    var params = {
      point: point,
      type: type,
      pointDesc: pointDesc
    }
    requst_post_addPoint(params).then(res => {
      if (type == app.globalData.plusPoint) {
        let point1 = app.globalData.userInfo.availablePoint + point;
        app.globalData.userInfo.availablePoint = point1
      } else {
        let point2 = app.globalData.userInfo.availablePoint - point;
        app.globalData.userInfo.availablePoint = point2
      }

    }).catch(err => {

    })
  },
  showAd() {
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
            wx.showToast({
              title: '广告加载失败，稍后来试哦~',
              icon: 'none'
            })
          })
      })
    }
  },
  downloadPicSuccess: function () {
    this.addUserPoint(app.globalData.subtractPoint, app.globalData.downloadPoint, this.data.picId?this.data.picId:this.data.item.sid)
  },
  downloadSuccess: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("授权数据" + res)
        if (res.authSetting['scope.writePhotosAlbum']) {
          console.log("授权成功")
          that.setData({
            showAdOk: 1 //显示广告
          })
          that.requestDown();
        } else {
          console.log("未授权")
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log("授权成功1")
              that.setData({
                showAdOk: 2 //显示广告
              })
              that.requestDown();
            },
            fail(e) {
              console.log(e)
              wx.showModal({
                content: '检测到您没打开相册授权，是否去设置打开？',
                confirmText: "确认",
                cancelText: "取消",
                success: function (res) {
                  //点击“确认”时打开设置页面
                  if (res.confirm) {
                    console.log('用户点击确认')
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                          that.setData({
                            showAdOk: 2 //显示广告
                          })
                          that.requestDown();
                        } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                          wx.showToast({
                            title: '获取权限失败,请确认相册权限是否开启',
                            icon: 'none'
                          })
                        }
                      }
                    })
                  } else {
                    console.log('用户点击取消')
                    wx.showToast({
                      title: '获取权限失败,请确认相册权限是否开启',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          })
        }
      }
    })


  },

  requestDown: function () {
    var that = this;
    var src = that.data.src
    if (app.globalData.userInfo.availablePoint > 0) {
      if (that.data.mainPicPath) {
        var mainPath;
        var secondPicPath;
        if (that.data.mainPicPath.indexOf("https") != 0) {
          mainPath = that.data.mainPicPath.replace("http", "https")
          secondPicPath = that.data.secondPicPath.replace("http", "https")
        }
        if (that.data.secondPicPath.indexOf("https") != 0) {
          secondPicPath = that.data.secondPicPath.replace("http", "https")
        }
        that.saveImg(mainPath);
        that.saveImg(secondPicPath);
      } else {
        if (src.indexOf("https") != 0) {
          src = src.replace("http", "https")
        }
        that.saveImg(src);
      }
      that.downloadPicSuccess()
    } else {
      wx.showToast({
        title: "积分不足，请看完广告获取积分",
        icon: 'none',
        duration: 2000
      })
      // that.showAd();
      that.setData({
        is_credit: true
      })
    }
    that.setData({
      showAdOk: 1
    })
  },

  saveImg: function (path) {
    var e = this
    wx.getImageInfo({
      src: path,
      success: function (t) {
        wx.saveImageToPhotosAlbum({
          filePath: t.path,
          success: function (t) {
            
            e.setData({
              is_downloaded: !0,
            })
          },
          fail: function (t) {},
          complete: function (t) {}
        });
      },
      fail: function (t) {},
      complete: function (t) {}
    })
  },
  
  copy: function (t) {
    var n = t.currentTarget.dataset.content;
    wx.setClipboardData({
      data: n,
      success: function () {
        wx.showToast({
          title: "复制完成",
          icon: "success",
          image: "",
          duration: 2000,
          mask: !0,
          success: function () {},
          fail: function () {},
          complete: function () {}
        });
      },
      fail: function () {},
      complete: function () {}
    });
  },
  appTips: function () {
    wx.setStorageSync("appTips", !0), this.setData({
      appTips: !1
    });
  },
  onShareAppMessage: function () {
    if (this.data.src != null && this.data.src != '') { //头像分享
      return {
        title: "咚，好友发给你一张头像、请查收！",
        path: "pages/photo/photo?picId=" + this.data.picId + "&src=" + this.data.src ,
        imageUrl: this.data.src
      };
    } else { //套图分享
      return {
        title: "咚，好友发给你一张头像、请查收！",
        path: "pages/photo/photo?item=" + JSON.stringify(this.data.item),
      };
    }

  }
});